#!/usr/bin/env bash

# 索引构建测试
RACE=-race
TIMEOUT=timeout
FAILED=0

# 系统检查（同wc测试）
if [[ "$OSTYPE" = "darwin"* ]]; then
  if go version | grep 'go1.17.[012345]'; then
    RACE=
    echo '*** Turning off -race since it may not work on a Mac'
    echo '    with ' `go version`
  fi
fi

if timeout 2s sleep 1 > /dev/null 2>&1; then
  :
else
  if gtimeout 2s sleep 1 > /dev/null 2>&1; then
    TIMEOUT=gtimeout
  else
    TIMEOUT=
    echo '*** Cannot find timeout command; proceeding without timeouts.'
  fi
fi
if [ "$TIMEOUT" != "" ]; then
  TIMEOUT+=" -k 2s 180s "
fi

# 创建测试目录
rm -rf mr-tmp
mkdir mr-tmp || exit 1
cd mr-tmp || exit 1
rm -f mr-*

# 构建程序和插件
(cd ../../mrapps && go clean)
(cd .. && go clean)
(cd ../../mrapps && go build $RACE -buildmode=plugin indexer.go) || exit 1
(cd .. && go build $RACE mrcoordinator.go) || exit 1
(cd .. && go build $RACE mrworker.go) || exit 1
(cd .. && go build $RACE mrsequential.go) || exit 1

# 生成正确输出
../mrsequential ../../mrapps/indexer.so ../pg*txt || exit 1
sort mr-out-0 > mr-correct-indexer.txt
rm -f mr-out*

echo '***' Starting indexer test.

# 启动协调器
$TIMEOUT ../mrcoordinator ../pg*txt &
sleep 1

# 启动多个工作节点
$TIMEOUT ../mrworker ../../mrapps/indexer.so &
$TIMEOUT ../mrworker ../../mrapps/indexer.so

# 收集并比较结果
sort mr-out* | grep . > mr-indexer-all
if cmp mr-indexer-all mr-correct-indexer.txt; then
  echo '---' indexer test: PASS
else
  echo '---' indexer output is not the same as mr-correct-indexer.txt
  echo '---' indexer test: FAIL
  FAILED=1
fi

# 等待所有进程退出
wait

exit $FAILED